package com.ktjy.gateway.filter;

import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.factory.AbstractNameValueGatewayFilterFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.UUID;

/**
 * AddHeaderTokenGatewayFilterFactory 自定义添加请求头Token网关过滤器工厂
 * 使用：filters: - AddHeaderToken=Token, uuid
 *
 * @author LILIBO
 * @since 2021-06-24
 */
@Component
public class AddHeaderTokenGatewayFilterFactory extends AbstractNameValueGatewayFilterFactory {

    @Override
    public GatewayFilter apply(NameValueConfig config) {
        return new GatewayFilter() {
            @Override
            public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
                // 响应之前在响应头添加Token，支持uuid、jwt等
                return chain.filter(exchange).then(Mono.fromRunnable(() -> {
                    HttpHeaders headers = exchange.getResponse().getHeaders();
                    String type = config.getValue();
                    String value = config.getValue();
                    if ("uuid".equalsIgnoreCase(type)) {
                        // 生成UUID
                        value = UUID.randomUUID().toString();
                    } else if ("jwt".equalsIgnoreCase(type)) {
                        // 生成JWT
                        value = generateToken();
                    }
                    headers.add(config.getName(), value);
                }));
            }
        };
    }

    /*
     * 生成JWT
     */
    private String generateToken() {
        return "eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIyMSIsImlzcyI6IkJvQm8iLCJleHAiOjE3MTEzNTkzMTMsImlhdCI6MTcxMTM1OTI4MywiYWNjb3VudCI6IumbquixuSIsImp0aSI6ImVjZWE1OWJjMTA2NzRmNGY5N2I1OGVjMDI5OThlMTk4In0.8OWU2VV6jMjhs0p_QhFuK3_XORuCvPMfDwRNWsjnOA0";
    }

}
